  <!-- 用户管理 -->
<template>
  <div class="main-body">
    <header class="main-body-search">
      <el-form :model="search" @submit.native.prevent>
        <el-row :gutter="50" type="flex" justify="space-between">
          <el-col :span="12">
            <el-button type="primary" @click="showDetail({})" icon="el-icon-plus">新建用户</el-button>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-form-item label class="nja-form-line">
              <el-input
                style="width: 300px;"
                v-model.trim="search.username"
                placeholder="账号或用户姓名"
                clearable
                @keyup.enter.native="searchHandle"
              >
                <div
                  slot="prefix"
                  style="height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;"
                >
                  <i class="el-icon-search"></i>
                </div>
                <el-button type="primary" slot="append" @click="searchHandle">查询</el-button>
              </el-input>
              <!-- <el-button type="primary" style="margin-left: 10px;" icon="el-icon-finished">筛选</el-button> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </header>
    <el-main class="main-body-table">
      <div class="table-shadow"></div>
      <el-table :data="tableData" stripe style="width: 100%" height="calc(100vh - 250px)">
        <el-table-column prop="username" label="账号" align="center" width="180"></el-table-column>
        <el-table-column prop="nickname" label="用户姓名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column prop="orgCode" label="所属机构" align="center">
          <template slot-scope="scope">{{ orgMap[scope.row.orgCode] }}</template>
        </el-table-column>
        <el-table-column prop="role" label="角色" align="center">
          <template slot-scope="scope">{{ types[scope.row.role] }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="-1"
              @change="changeUserStatus(scope.row.id)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="210px">
          <template slot-scope="scope">
            <div style="display: flex;">
              <el-button size="mini" type="primary" @click="showDetail(scope.row)">编辑</el-button>
              <el-button size="mini" type="warning" @click="updatePwd(scope.row)">重置</el-button>
              <el-button
                size="mini"
                v-if="scope.row.username != 'admin'"
                type="danger"
                @click="deleteRow(scope.row)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"></el-empty>
        </template>
      </el-table>
      <!--工具条-->
      <el-pagination
        background
        class="main-body-table-page"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        :current-page="search.current"
        :page-size="search.size"
        :total="search.total"
      ></el-pagination>
    </el-main>
    <el-dialog
      :title="form.id ? '编辑用户' : '新增用户'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      center
      v-dialogDrag
      custom-class="mydialog"
      width="700px"
    >
      <el-form ref="form" class="formlayout" :model="form" label-width="90px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="照片">
              <div class="face-img">
                <el-upload
                  class="avatar-uploader"
                  action
                  :auto-upload="false"
                  :on-change="onChange"
                  :show-file-list="false"
                >
                  <el-image
                    v-if="userPhoto && userPhoto.url"
                    :src="userPhoto.url"
                    fit="contain"
                    class="avatar hidden"
                  ></el-image>
                  <div class="avatar-uploader-icon">
                    <i class="el-icon-plus" :class="userPhoto && userPhoto.url ? 'hiddle' : ''"></i>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="dccform-line"
              label="账号"
              prop="username"
              required
              :rules="[{required: true, message: '必填'}]"
            >
              <el-input v-model="form.username" placeholder="请输入账号" :disabled="!!form.id"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="dccform-line"
              label="用户姓名"
              prop="nickname"
              required
              :rules="[{required: true, message: '必填'}]"
            >
              <el-input v-model="form.nickname" placeholder="请输入用户姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="dccform-line"
              label="手机号"
              prop="phone"
              required
              :rules="[{required: true, message: '必填'}]"
            >
              <el-input v-model.number="form.phone" :maxlength="11" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="所属机构"
              prop="orgCode"
              required
              :rules="[{required: true, message: '必填'}]"
            >
              <el-cascader
                style="width: 100%;"
                v-model="form.orgCode"
                filterable
                :options="orgTree"
                :props="defaultProps"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="dccform-line"
              label="登录密码"
              prop="password"
              v-if="!form.id"
              required
              :rules="[{required: true, message: '必填'}]"
            >
              <el-input v-model="form.password" placeholder="请输入登录密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="dccform-line"
              label="角色"
              prop="role"
              required
              :rules="[{required: true, message: '必填'}]"
            >
              <el-select v-model="form.role" style="width: 100%;">
                <el-option :label="r.role" :value="r.id" v-for="(r, i) in roles" :key="i"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" style="width: 120px;" @click="saveHandle">保存</el-button>
        <el-button style="width: 120px;" @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  RegisterRequest,
  SelectListRole,
  selectFiles,
  UploadFile,
  GetFileBase64
} from '@/api'
import {
  SelectUserPage,
  UpdateUserStatus,
  RegisterUpdateUser,
  DeleteHandle
} from '@/api/admin/user'
import { SelectList } from '@/api/admin/org'
import { md5 } from '@/util/crypto'
import { toTree } from '@/util/common.js'
export default {
  data() {
    return {
      dialogVisible: false,
      search: {
        current: 1,
        size: 20,
        total: 0,
        username: '',
        nickname: ''
      },
      types: {},
      roles: [],
      form: {
        username: '',
        nickname: '',
        password: '',
        role: ''
      },
      orgMap: {},
      orgTree: [],
      defaultProps: {
        emitPath: false,
        checkStrictly: true,
        children: 'children',
        label: 'fullName',
        value: 'id'
      },
      userPhoto: null,
      tableData: []
    }
  },
  methods: {
    onChange(file) {
      console.log(file)
      if (!this.beforeAvatarUpload(file)) {
        return
      }
      file.url = URL.createObjectURL(file.raw)
      this.userPhoto = file
    },
    beforeAvatarUpload(file) {
      file.type = file.raw.type
      const isJPG =
        ['image/jpg', 'image/png', 'image/jpeg'].indexOf(file.type) !== -1
      const isLt5M = file.raw.size / 1024 / 1024 < 50
      if (!isJPG) {
        this.$message.error('上传文件只能是 jpg/png格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 50MB!')
      }
      return isJPG && isLt5M
    },
    loadImgData(refId) {
      // 加载图片
      selectFiles({
        refId: refId,
        type: 'userPhoto'
      }).then(async (res) => {
        console.log('selectFiles', res)
        if (res.code === 20000 && res.data && res.data.length > 0) {
          let file = res.data[0]
          let dataText = await GetFileBase64({
            id: file.id
          }).then((res) => {
            console.log('GetFileBase64', res)
            return res.code === 20000 && res.data
          })
          this.userPhoto = {
            status: 'finish',
            id: file.id,
            uid: file.id,
            url: `data:image/jpeg;base64,${dataText}`
          }
        }
      })
    },
    showDetail(row) {
      this.form = Object.assign(
        {
          username: '',
          nickname: '',
          password: '',
          role: ''
        },
        row
      )
      this.userPhoto = null
      this.dialogVisible = true
      this.$nextTick(() => {
        if (row.id) {
          this.loadImgData(row.id)
        }
        this.$refs.form.clearValidate()
      })
    },
    deleteRow(row) {
      console.log(row)
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteHandle({ id: row.id }).then((res) => {
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.loadData()
          }
        })
      })
    },
    async uploadFile(refId) {
      this.loading = true
      let formData = new FormData()
      if (this.userPhoto && this.userPhoto.status != 'finish') {
        formData.append('file', this.userPhoto.raw)
        formData.append('name', this.userPhoto.name)
        formData.append('size', this.userPhoto.size)
        formData.append('type', 'userPhoto')
        formData.append('refId', refId)
        return UploadFile(formData, (e) => {
          console.log('进度', e)
        }).then((res) => {
          console.log('UploadFile', res)
          this.loading = false
          this.userPhoto.status = 'finish'
        })
      }
    },
    saveHandle() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 保存
          let params = Object.assign({}, this.form)
          let API = RegisterRequest
          if (params.id) {
            API = RegisterUpdateUser
            delete params.password
          } else {
            params.password = md5(params.password)
          }
          delete params.lastUpdateTime
          delete params.createTime
          API(params).then(async (res) => {
            console.log('RegisterRequest', res)
            if (res.code === 20000) {
              // // 保存图片
              if (this.userPhoto && this.userPhoto.status !== 'finish') {
                await this.uploadFile(params.id || res.data)
              }
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.dialogVisible = false
              this.loadData()
            }
          })
        }
      })
    },
    updatePwd(row) {
      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '格式不正确'
      }).then(({ value }) => {
        // 修改密码
        RegisterUpdateUser({
          username: row.username,
          password: md5(value)
        }).then((res) => {
          console.log('RegisterUpdateUser', res)
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
            this.loadData()
          }
        })
      })
    },
    handleCurrentChange(val) {
      this.search.current = val
      this.loadData()
    },
    searchHandle() {
      this.search.current = 1
      this.loadData()
    },
    changeUserStatus(id) {
      UpdateUserStatus({ id }).then((res) => {
        console.log('UpdateUserStatus', res)
      })
    },
    loadOrgData() {
      SelectList({})
        .then((res) => {
          console.log('success:', res)
          let map = {}
          res.data.forEach((d) => {
            map[d.id] = d.fullName
          })
          this.orgMap = map
          this.orgTree = toTree(res.data)
        })
        .catch((err) => {
          console.log('err:', err)
        })
    },
    loadData() {
      SelectUserPage(this.search)
        .then((res) => {
          console.log('success:', res)
          this.tableData = res.data.records
          this.search.total = res.data.total
        })
        .catch((err) => {
          console.log('err:', err)
        })
    },
    loadDict() {
      SelectListRole().then((res) => {
        console.log('SelectListRole', res)
        if (res.code === 20000) {
          this.types = {}
          this.roles = res.data.map((d) => {
            this.types[d.id] = d.role
            return d
          })
        }
      })
    }
  },
  mounted() {
    this.loadOrgData()
    this.loadDict()
    this.loadData()
  }
}
</script>

<style lang="scss" scoped>
.tableimg {
  width: 45px;
}
.formlayout {
  padding: 20px 40px;
}

$imgwidth: 155px;

.face-img {
  position: relative;
  height: $imgwidth;
  width: $imgwidth;
  background-color: #f1f2f3;
  // border: 1px solid #eee;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .hiddle {
    visibility: hidden;
  }
  .avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    cursor: pointer;
    height: $imgwidth;
    width: $imgwidth;
    &:hover {
      .avatar-uploader-icon {
        background-color: rgba(200, 200, 200, 0.5);
      }
      .hiddle {
        visibility: visible;
      }
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    position: absolute;
    left: 0px;
    right: 0px;
    bottom: 0px;
    top: 0px;
    font-size: 28px;
    color: #409eff;
    display: flex;
    align-items: center;
    justify-content: center;
    i {
      font-size: 30px;
    }
  }

  .avatar {
    height: $imgwidth;
    width: $imgwidth;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
